package com.yonyou.cyxdms.sysAuth.service.service.impl;

import com.yonyou.cyx.framework.compent.redis.RedisClient;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysAuth.service.entity.TtUserLoginPO;
import com.yonyou.cyxdms.sysAuth.service.mapper.TtUserLoginMapper;
import com.yonyou.cyxdms.sysAuth.service.service.TtUserLoginService;
import com.yonyou.cyxdms.sysmanage.client.constants.BaseDataCommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.MessageFormat;
import java.time.LocalDateTime;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 李贺
 * @since 2019-12-10
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class TtUserLoginServiceImpl implements TtUserLoginService {

    @Autowired
    TtUserLoginMapper ttUserLoginMapper;

    @Autowired
    RedisClient redisClient;

    /**
     * 更新登录信息
     * 2019/12/10
     *
     * @param id
     * @param loginInfoDto
     */
    @Override
    @Async("asyncPoolTaskExecutor")
    public void upLog(Long id, String jwt, Integer type, LoginInfoDto loginInfoDto) {
        TtUserLoginPO ttuserloginpo = ttUserLoginMapper.selectById(id);
        ttuserloginpo.setOrgId(loginInfoDto.getOrgId());
        ttuserloginpo.setLastOperateDate(LocalDateTime.now());
        ttuserloginpo.setOwnerCode(loginInfoDto.getOwnerCode());
        ttuserloginpo.setCompanyId(loginInfoDto.getCompanyId());
        ttuserloginpo.setUserOrgId(loginInfoDto.getUserOrgId());
        if (!StringUtils.isNullOrEmpty(jwt)) {
            ttuserloginpo.setJwt(jwt);
        }
        if (type == 10041001) {
            ttuserloginpo.setLogOutDate(LocalDateTime.now());
        }
        ttUserLoginMapper.updateById(ttuserloginpo);
        String format = MessageFormat.format(BaseDataCommonConstants.USER_LOGIN, id);
        redisClient.set(format, 1, BaseDataCommonConstants.USER_LOGIN_MIN);
    }

}
